package com.neusoft.neuiotms.dcom.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcom.converter.MonthValueAddedConverter;
import com.neusoft.neuiotms.dcom.dto.MonthValueAddedDTO;
import com.neusoft.neuiotms.dcom.model.MonthValueAdded;
import com.neusoft.neuiotms.dcom.model.MonthWeekly;
import com.neusoft.neuiotms.dcom.repository.MonthValueAddedRepository;
import com.neusoft.neuiotms.dcom.repository.MonthWeeklyRepository;
import com.neusoft.neuiotms.dcom.service.MonthValueAddedService;

@Service
public class MonthValueAddedServiceImpl implements MonthValueAddedService {

    @Autowired
    private MonthValueAddedConverter monthValueAddedConverter;
    @Autowired
    private MonthValueAddedRepository monthValueAddedRepository;
    @Autowired
    private MonthWeeklyRepository monthWeeklyRepository;

    @Override
    public List<MonthValueAddedDTO> getInfoByMonthId(final Long monthId) {
        final List<MonthValueAdded> list = this.monthValueAddedRepository.findByMonthId(monthId);
        return this.monthValueAddedConverter.toListDTO(list);
    }

    @Transactional
    @Override
    public List<MonthValueAddedDTO> update(final Long monthId, final List<MonthValueAddedDTO> dtos) {

        MonthWeekly model;
        try {
            model = this.monthWeeklyRepository.getOne(monthId);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException("未找到对应的月报！");
        }

        final List<MonthValueAdded> models = new ArrayList<>();

        this.monthValueAddedRepository.deleteByMonthId(monthId);

        dtos.stream().map(l -> {
            final MonthValueAdded item = this.monthValueAddedConverter.toModel(l);
            item.setMonth(model);
            return item;
        }).forEach(models::add);

        if (models.size() > 0) {
            this.monthValueAddedRepository.saveAll(models);
        }

        return this.monthValueAddedConverter.toListDTO(models);
    }

}
